<?

/*	Created by Alexander Alexandrov aka SS

			hazg@mail.ru				*/
include('log.class.php');

$sslib_err_exception = array();

function catchFatalErrors($p_OnOff='On'){
    ini_set('display_errors','On');
    if(is_array($_SERVER)&&array_key_exists('HTTP_HOST',$_SERVER))
    {
    	$phperror1='</a></script></iframe></option></select></table></body></html><div style="margin:2px;background-color: buttonface; border: 1px solid buttonshadow;font: message-box; color: windowtext;"><h1>FATAL</h1>';
    	$phperror2='</div>';
    }
    else 
    {
    	$phperror1=/*__T('fatal error').'*/'FATAL: ';
    	$phperror2="\n";
    }
    
    ini_set('error_prepend_string',$phperror1);
    ini_set('error_append_string',$phperror2);
}
catchFatalErrors();

error_reporting(E_ERROR | E_PARSE  | E_WARNING | E_NOTICE);
ini_set("error_reporting", E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set("display_errors", "on");
define('SSLIB_Err', TRUE);

set_exception_handler("sslib_exception_handler");
set_error_handler("sslib_error_handler");

//register_shutdown_function("sslib_shutdown");
/*function sslib_shutdown()
{
	$arr = error_get_last();
	sslib_error_handler($arr['number'], $arr['meassage'], $arr['file'], $arr['line']);
}*/
function sslib_error_ignore($errno)
{
    if(!Sslib::Debug()) return true;
	$arr = explode(' ',Sslib::Variable('sslib.error.ignore'));
	
	if(is_array($arr))
	foreach($arr as $a)
	{
		if($errno == trim($a))
			return true;
	}
	return false;
}
function sslib_error_handler($errno, $errstr, $errfile, $errline)
{
	if(sslib_error_ignore($errno)) return;
	
	/*$handlers = ob_list_handlers();
	while (!empty($handlers) )    
	{
		ob_end_clean();
	    $handlers = ob_list_handlers();
	}*/
	
	Log::Error("$errstr in $errfile($errline) [$errno]");
	//print(sslib_exception_format($errno, $errstr, $errfile, $errline, __T('error')));
	print sslib_exception_format($errno, $errstr, $errfile, $errline, __T('error'));
	exit;
}
/* Handle exceptions
 * 
 * @param Exception $exc
 */
function sslib_exception_handler($exc)
{
	if(sslib_error_ignore($exc->getCode())) return;
	Log::Error($exc->getMessage().' in '.$exc->getFile().'('.$exc->getLine().')'.' ['.$exc->getCode().']');
	$res = (get_class($exc) == "Exception")?sslib_exception_format($exc->getCode(), $exc->getMessage(), $exc->getFile(), $exc->getLine(), 'Exception'):$exc->__toString();
	print $res;
	/*if(class_exists("Page"))
		Page::Draw();*/
	exit;
}


function sslib_exception_format($errno, $errstr, $errfile, $errline, $header = "", $exc = null)
{
	if(!(is_array($_SERVER)&&array_key_exists('HTTP_HOST',$_SERVER)))
	{
		return "\n_________________________________\n".__T('error').' ['.$errno.']: '.preg_replace('#\[LONGTEXT\](.*?)\[/LONGTEXT\]#is','$1',$errstr).' '.$errfile.'('.$errline.")\n";
	}
	
	/*$handlers = ob_list_handlers();
	while ( ! empty($handlers) )    
	{
    	ob_end_clean();
    	$handlers = ob_list_handlers();
	}*/
	$errstr = preg_replace('#\[LONGTEXT\](.*?)\[/LONGTEXT\]#is','<br />	<textarea rows="10" cols="100">$1</textarea>',$errstr);
	global $cur_exec_file;
	$aCallstack = null;
	if($exc == null)
	{
		$aCallstack = debug_backtrace();
	}
	else
	{
		$aCallstack = $exc->getTrace();
	}
	
	$rand = RandomKey();
	$host = Request::Host();
$ret = '</a></script></iframe></option></select></table></body></html>
<div style="position:relative; z-index:1000;margin:2px;padding-left:10px;padding:2px;background-color: infobackground; border: 1px solid buttonshadow;font:message-box; color: windowtext;">
<div style="background: activecaption;border:activeborder 1px solid;"><strong style="margin-left:0px;">'.$header.'</strong>'."<small>[$errno]</small>".'</div>
'."<pre>".$errstr."</pre> in $errfile</a>:$errline".
'<a style="text-decoration: none;" href="#" onclick="var s = document.getElementById(\''.$rand.'\');s.style.display=((s.style.display==\'none\')?\'\':\'none\');">
&gt;&gt;&gt;
</a>
<div style="display:none;" id="'.$rand.'">'
;
    $sOut="";
   if(is_array($aCallstack)){
   $stack = "<table style=\"border: collapsed;font:message-box; color:inactivecaptiontext;font-size:smaller;\">";//<thead><tr><th>file</th><th>line</th><th>function</th>"."</tr></thead>";
    
    $aCallstack = array_reverse($aCallstack);
    $stacknum = 0; 
    foreach($aCallstack as $aCall)
    {
    	if($aCall["function"] == "sslib_error_handler" || $aCall["function"] == 'sslib_exception_handler') break;
    	$stacknum ++;
        if (!isset($aCall['file'])) $aCall['file'] = '[PHP Kernel]';
        if (!isset($aCall['line'])) $aCall['line'] = '';
		if(stripos($aCall["file"],'/pages/') !== FALSE) $aCall['file']='<strong><i>'.$aCall['file'].'</i></strong>';
        $stack .= "<tr><td>{$aCall["file"]}</td><td>{$aCall["line"]}</td>".
            "<td>{$aCall["function"]}</td></tr>";
    }
    $stack .= "</table>";
    $inculdes = '';
    $defined = get_defined_constants(true);
    //$ret.=print_r($defined, true);
    
	foreach ($defined['user'] as $key => $val) {
		if(/*is_string($glob) &&*/ (strpos($key, 'SSLIB_') !== false))
		{
			
			$inculdes.=' '. substr($key, 6);
		}
	}
    if($stacknum  > 0) $ret.=$stack;
    if($inculdes) $ret.='<p style="margin:0px;color:inactivecaptiontext;font-size:smaller;font-weight:bold;">'.__T('includes').': '.$inculdes.'</p>';
    }
	$errstr = nl2br($errstr);
	return $ret.'</div></div>';
}
function sslib_format_stack($arr)
{
	
}

class Err extends Exception
{
	function __construct($message, $code = 0)
	{
		parent::__construct($message, $code);
		die($this->__toString());
	}
	function __toString()
	{
		return sslib_exception_format($this->getCode(), $this->getMessage(), $this->getFile(), $this->getLine(), __T('error'), $this);
	}
	function __destruct()
	{   
		/*if(class_exists('Page'))
			Page::Draw();*/
	}
}

?>